package indi.simple.pms.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import indi.simple.pms.auth.PermitAll;
import indi.simple.pms.entity.dataobject.SystemLogDO;
import indi.simple.pms.entity.viewobject.SystemDashboardVO;
import indi.simple.pms.entity.viewobject.CommonResultVO;
import indi.simple.pms.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wanglunhui
 * @Date: 2021/6/7 23:22
 * @Description:
 */
@RestController
@RequestMapping("/system/common")
@RequiredArgsConstructor
public class SystemCommonController {

    private final SystemUserService systemUserService;
    private final SystemRoleService systemRoleService;
    private final SystemDepartmentService systemDepartmentService;
    private final SystemJobService systemJobService;
    private final SystemLogService systemLogService;

    @GetMapping("/get/dashboard")
    @PermitAll
    public CommonResultVO<?> getDashboard(){
        LocalDateTime now=LocalDateTime.now();

        // 用户数量
        long userCount= systemUserService.count();

        // 角色数量
        long roleCount= systemRoleService.count();

        // 部门数量
        long departmentCount=systemDepartmentService.count();

        // 职位数量
        long jobCount= systemJobService.count();

        // 如果今天周六，todayOfWeek为DayOfWeek.SATURDAY，mondayToToday为5
        DayOfWeek todayOfWeek=now.getDayOfWeek();
        int mondayToToday=todayOfWeek.compareTo(DayOfWeek.MONDAY);// 从周一到今天的天数
        List<Long> thisWeekLogCountList=new ArrayList<>();
        for (int i=mondayToToday;i>=0;i--){// 本周内今天之前的从数据库获取
            LocalDateTime that=now.plusDays(-i);// 减去天数得到那天的日期

            long thatDayLogCount= systemLogService.count(Wrappers.<SystemLogDO>lambdaQuery().apply("date(create_time)={0}",that.toLocalDate().toString()));

            thisWeekLogCountList.add(thatDayLogCount);
        }
        for (int i=thisWeekLogCountList.size()+1;i<=7;i++){// 本周内今天之后的都为0，因为还没到那天
            thisWeekLogCountList.add(0L);
        }

        SystemDashboardVO systemDashboardVO=new SystemDashboardVO();
        systemDashboardVO.setUserCount(userCount);
        systemDashboardVO.setRoleCount(roleCount);
        systemDashboardVO.setDepartmentCount(departmentCount);
        systemDashboardVO.setJobCount(jobCount);
        systemDashboardVO.setThisWeekLogCountList(thisWeekLogCountList);

        return CommonResultVO.success(systemDashboardVO);
    }

}
